import requests
import json
import os
import base64
import binascii
from Crypto.Cipher import AES


def aesEncrypt(text, secKey):
    pad = 16 - len(text) % 16
    text = text + pad * chr(pad)
    encryptor = AES.new(secKey, 2, '0102030405060708')
    ciphertext = encryptor.encrypt(text)
    ciphertext = base64.b64encode(ciphertext)
    return ciphertext.decode()


def rsaEncrypt(text, pubKey, modulus):
    text = text[::-1].encode()
    rs = int(binascii.hexlify(text), 16)**int(pubKey, 16) % int(modulus, 16)
    return format(rs, 'x').zfill(256)


def createSecretKey(size):
    return ''.join( [ hex(x)[2:] for x in os.urandom(size) ] )[0:16]

def netease_api(url, params):
    headers = {
      'Origin': 'http://music.163.com',
      'X-Real-IP': '118.88.88.88',
      'Accept-Language': 'q=0.8,zh-CN;q=0.6,zh;q=0.2',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
      'Referer': 'http://music.163.com/',
      'Cookie': 'os=uwp;'
    }
    modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
    nonce = '0CoJUm6Qyw8W8jud'
    pubKey = '010001'
    text = json.dumps(params)
    secKey = createSecretKey(16)
    encText = aesEncrypt(aesEncrypt(text, nonce), secKey)
    encSecKey = rsaEncrypt(secKey, pubKey, modulus)
    data = {
        'params': encText,
        'encSecKey': encSecKey
    }
    s = requests.session()
    r = s.post(url, headers=headers, data=data)
    result = json.loads(r.text)
    return result


def music_mp3_url(music_id, rate=128000):
    params = {
        "ids":"[%d]" % music_id,
        "br": rate
    }
    res = netease_api('http://music.163.com/weapi/song/enhance/player/url?csrf_token=', params)
    return res['data'][0]['url']


def search_music(keywords):
    params = {
        "s": keywords,
        "type": 1,
        "offset": 0,
        "total": True,
        "limit": 2
    }
    res = requests.post('http://music.163.com/api/search/pc', data=params)
    result = json.loads(res.text)
    res = [{"id": item['id'], "name": "%s(作者:%s)" % (item['name'], item['artists'][0]['name'])} for item in result['result']['songs']]
    return res


if __name__ == "__main__":
    res = music_mp3_url(186411)
    # res = search_music("海阔")
    print(res)
    pass
